from musiclib.musiccrawler.googlemusic.core import Search
from musiclib.musiccrawler.googlemusic.fileOPWrapper import myreadlines
import urllib
import simplejson
import time

def getsonglist():
    """
    song file list in file data/songlist.txt
    """
    results = []
    fname = "./data/songlist.txt"
    lines = myreadlines(fname)
    for line in lines:
        line = line.strip()
        ws = line.split(";")
        dic = {}
        dic['song'] = ws[1]
        dic['artist'] = ws[0]
        dic['region'] = ws[2]
        results.append(dic)
    return results
        

def getfirstsong(songstr):
    sobj = Search(songstr)
    songs = sobj.load_songs()
    if len(songs) == 0:
        return None
    else:
        return songs[0]

"""
if __name__ == "__main__":
    songlist =  getsonglist()
    errorfilerecord = ""
    for song in songlist:
        time.sleep(5)
        searchstr = song['song']+song['artist']
        searchstr = urllib.quote(searchstr)
        thesong = getfirstsong(searchstr)
        if thesong == None:
            #add to errorfilerecord
            raise Exception("error file record")
        else:
            thesong.load_download()
            thesong.lyric_load_download()
            getattr(thesong,"downloadUrl")
            getattr(thesong,"lyricdownloadUrl")
            #create a file for each song


    #print songlist[0]
    #thesong = getfirstsong("good%20times%20bad%20times")
    thesong = getfirstsong("led%20zeppelin%20good%20times%20bad%20times")    
    #thesong = getfirstsong("times")
    
    #this does not work
    #thesong.load_streaming()
    #print getattr(thesong,"songUrl")
    
    thesong.load_download()
    print getattr(thesong,"downloadUrl")

    #thesong.lyric_load_download()
    #print getattr(thesong,"lyricdownloadUrl")
"""
